package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.RedisSimpleLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

import static com.hmdp.utils.RedisConstants.LOCK_ORDER_KEY;
import static com.hmdp.utils.RedisConstants.LOCK_ORDER_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    private static DefaultRedisScript<Long> redisScript;
    static {
        redisScript = new DefaultRedisScript<>();
        redisScript.setLocation(new ClassPathResource("seckill.lua"));
        redisScript.setResultType(Long.class);
    }

    private ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    // @PostConstruct
    public void init() {
        SECKILL_ORDER_EXECUTOR.submit(new SeckillOrderHandler());
    }


/*    private BlockingQueue<VoucherOrder> SECKILL_ORDER_QUEUE = new ArrayBlockingQueue<>(1024 * 1024);
    private class SeckillOrderHandler implements Runnable{
        @Override
        public void run() {
            while(true) {
                try {
                    VoucherOrder order = SECKILL_ORDER_QUEUE.take();
                    proxy.createOrder(order);
                } catch (InterruptedException e) {
                    log.error("订单创建失败！" + e);
                }
            }
        }
    }*/

    private class SeckillOrderHandler implements Runnable{
        private static final String ORDER_QUEUE = "stream.orders";
        @Override
        public void run() {
            while(true) {
                try {
                    // 读取消息队列XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> recordList = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofMinutes(2)),
                            StreamOffset.create(ORDER_QUEUE, ReadOffset.lastConsumed())
                    );
                    // 未读取到消息，循环
                    if (recordList == null || recordList.isEmpty()) {
                        continue;
                    }
                    // 成功读取到消息，解析
                    MapRecord<String, Object, Object> record = recordList.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder order = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), false);
                    // 执行创建订单任务
                    proxy.createOrder(order);
                    // 发送ACK确认 XACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(ORDER_QUEUE, "g1", record.getId());
                } catch (Exception e) {
                    log.error("订单创建失败！", e);
                    handlePendingList(e);
                }
            }
        }

        private void handlePendingList(Exception e) {
            while (true) {
                try {
                    // 读取pending-list  XREADGROUP GROUP g1 c1 COUNT 1 STREAMS stream.orders 0
                    List<MapRecord<String, Object, Object>> recordList = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(ORDER_QUEUE, ReadOffset.from("0"))
                    );
                    // 未读取到消息，结束循环
                    if (recordList == null || recordList.isEmpty()) {
                        break;
                    }
                    // 成功读取到消息，解析
                    MapRecord<String, Object, Object> record = recordList.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder order = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), false);
                    // 执行创建订单任务
                    proxy.createOrder(order);
                    // 发送ACK确认 XACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(ORDER_QUEUE, "g1", record.getId());
                } catch (Exception ex) {
                    log.error("处理pending-list过程中出现异常", e);
                }
            }
        }
    }

    @Transactional
    public void createOrder(VoucherOrder order) {
        // 扣减库存
        seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", order.getVoucherId())
                .gt("stock", 0)
                .update();
        // 创建订单插入
        save(order);
    }

    private IVoucherOrderService proxy;
    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        // 创建订单
        long orderId = redisIdWorker.nextId("order");
        // 执行lua脚本
        Long result = stringRedisTemplate.execute(redisScript,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), String.valueOf(orderId));
        int res = result.intValue();
        if (res != 0) {
            // 秒杀失败
            String msg = res == 1 ? "优惠卷已抢完！" : "此优惠卷不能重复购买！";
            return Result.fail(msg);
        }
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        // 返回订单id
        return Result.ok(orderId);
    }


/*    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        // 执行lua脚本
        Long result = stringRedisTemplate.execute(redisScript,
                Collections.emptyList(),
                voucherId.toString(), userId.toString());
        int res = result.intValue();
        if (res != 0) {
            // 秒杀失败
            String msg = res == 1 ? "优惠卷已抢完！" : "此优惠卷不能重复购买！";
            return Result.fail(msg);
        }
        // 将数据存入阻塞队列，异步操作数据库，扣减库存并插入订单
        // 创建订单
        long orderId = redisIdWorker.nextId("order");
        VoucherOrder order = new VoucherOrder();
        order.setId(orderId);
        order.setVoucherId(voucherId);
        order.setUserId(userId);
        // 将订单放入阻塞队列
        try {
            SECKILL_ORDER_QUEUE.put(order);
        } catch (InterruptedException e) {
            log.error("订单加入阻塞队列失败！", e);
        }
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        // 返回订单id
        return Result.ok(orderId);
    }*/


/*    *//**
     * 秒杀优惠卷
     * @param voucherId
     * @return
     *//*
    @Override
    public Result seckillVoucher(Long voucherId) {
        // 查询优惠卷信息
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        // 判断秒杀是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            // 未开始
            return Result.fail("秒杀未开始");
        }
        // 判断秒杀是否结束
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            // 已结束
            return Result.fail("秒杀已结束");
        }
        // 判断库存是否充足
        if (voucher.getStock() < 1) {
            // 无库存
            return Result.fail("优惠卷已抢完");
        }

        Long userId = UserHolder.getUser().getId();
        // 加分布式锁
        //RedisSimpleLock redisSimpleLock = new RedisSimpleLock(stringRedisTemplate, LOCK_ORDER_TTL, TimeUnit.MINUTES, LOCK_ORDER_KEY + userId);
        //boolean success = redisSimpleLock.tryLock();
        RLock lock = redissonClient.getLock(LOCK_ORDER_KEY + userId);
        boolean success = lock.tryLock();
        if (!success) {
            // 加锁失败，返回错误
            return Result.fail("此优惠卷不能重复购买！");
        }
        try {
            // 获取代理对象（使用事务）
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createOrder(voucherId);
        } catch (IllegalStateException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            //redisSimpleLock.unLock();
            lock.unlock();
        }
    }*/

/*    @Transactional
    public Result createOrder(Long voucherId) {
        // 判断当前用户是否已经购买过此优惠券
        Long userId = UserHolder.getUser().getId();
        Integer count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if (count > 0) {
            // 存在对应订单，购买失败
            return Result.fail("此优惠卷不能重复购买！");
        }
        // 有库存，扣减
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0)
                .update();
        if (!success) {
            // 无库存
            return Result.fail("优惠卷已抢完");
        }
        // 创建订单插入
        long orderId = redisIdWorker.nextId("order");
        VoucherOrder order = new VoucherOrder();
        order.setId(orderId);
        order.setVoucherId(voucherId);
        order.setUserId(userId);
        save(order);

        // 返回订单id
        return Result.ok(orderId);
    }*/
}
